package stat

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

type RequestGraylogAPIRes struct {
	Time         int     `json:"time"`
	Count        int     `json:"count"`
	Sum          float64 `json:"sum"`
	SumOfSquares float64 `json:"sum_of_squares"`
	Mean         float64 `json:"mean"`
	Min          float64 `json:"min"`
	Max          float64 `json:"max"`
	Variance     float64 `json:"variance"`
	StdDeviation float64 `json:"std_deviation"`
	Cardinality  int     `json:"cardinality"`
}

func RequestGraylogAPI(graylogUrl, field, query string, from, to time.Time) (data *RequestGraylogAPIRes, err error) {
	from = from.Add(-time.Hour * 8)
	to = to.Add(-time.Hour * 8)
	u := url.Values{}
	u.Add("field", field)
	u.Add("query", query)
	u.Add("from", from.Format("2006-01-02 15:04:05"))
	u.Add("to", to.Format("2006-01-02 15:04:05"))

	uri, _ := url.Parse(fmt.Sprintf("http://%s/api/search/universal/absolute/stats", graylogUrl))
	uri.RawQuery = u.Encode()
	req, err := http.NewRequest("GET", uri.String(), nil)
	if err != nil {
		return
	}

	req.SetBasicAuth("jigsaw", "jigsaw")
	req.Header.Set("Accept", "application/json")
	clt := http.Client{}
	res, err := clt.Do(req)
	if err != nil {
		return
	}
	defer res.Body.Close()
	data = new(RequestGraylogAPIRes)
	content, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}

	err = json.Unmarshal(content, data)
	return
}

func GenDate(t time.Time) (date int) {
	return t.Year()*10000 + int(t.Month())*100 + t.Day()
}

func GenWeekDay(date int) string {
	d := time.Date(date/10000, time.Month((date%10000)/100), date%100, 0, 0, 0, 0, time.UTC)
	weekDay := map[time.Weekday]string{
		time.Sunday:    "周日",
		time.Monday:    "周一",
		time.Tuesday:   "周二",
		time.Wednesday: "周三",
		time.Thursday:  "周四",
		time.Friday:    "周五",
		time.Saturday:  "周六",
	}[d.Weekday()]
	return fmt.Sprintf("%d-%d(%s)", date%10000/100, date%100, weekDay)
}
